#include <string>
#include <iostream>
#include <cstring>
#include <limits>
#include <thread>
#include <chrono>
#include "./db_manager/protocol/protocol.h"
#include "db_common.h"
// #include "db_binary_serialization.h"
#include "db_manager/utils/socket_utils.hpp"

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#elif defined(__linux__)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>     // Linux 系统调用 (close)
#include <sys/socket.h> // Socket 核心头文件
#include <netinet/in.h> // 网络地址结构 (sockaddr_in)
#include <arpa/inet.h>  // IP 地址转换 (inet_pton)
#include <getopt.h>     // Linux 命令行参数解析库
#include <errno.h>      // for errno
#endif
#include "db_manager/conf/config.h"

// 默认服务器地址和端口
#define DEFAULT_HOST "127.0.0.1"
#define DEFAULT_PORT 7092
#define BUFFER_SIZE 1024

// 程序用法提示
void print_usage(const char *prog_name)
{
    fprintf(stderr,
            "Usage: %s [OPTIONS]\n"
            "Options:\n"
            "  -u, --user <USER> User name (required)\n"
            "  -p, --password <PASSWORD> User password (required)\n"
            "  -h, --host <IP>   Server IP address (not required, e.g., 127.0.0.1)\n"
            "  -o, --port <NUM>  Server port number (not required, e.g., 8080)\n"
            "  -?, --help        Show this help message\n",
            prog_name);
}

#ifdef _WIN32
// 解析命令行参数
void parse_arguments(int argc, char *argv[], std::string &host, int &port, std::string &username, std::string &password)
{
    for (int i = 1; i < argc; i++)
    {
        if ((strcmp(argv[i], "-host") == 0 || strcmp(argv[i], "-h") == 0) && i + 1 < argc)
        {
            host = argv[i + 1];
            i++;
        }
        else if ((strcmp(argv[i], "-port") == 0 || strcmp(argv[i], "-o") == 0) && i + 1 < argc)
        {
            port = atoi(argv[i + 1]);
            i++;
        }
        else if (strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "--help") == 0)
        {
            print_usage(argv[0]);
            exit(0);
        }
        else if ((strcmp(argv[i], "-u") == 0 || strcmp(argv[i], "--user") == 0) && i + 1 < argc)
        {
            username = argv[i + 1];
            i++;
        }
        else if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--password") == 0) && i + 1 < argc)
        {
            password = argv[i + 1];
            i++;
        }
        else
        {
            std::cerr << "unrecognized argument: " << argv[i] << std::endl;
            exit(1);
        }
    }
}

int main(int argc, char *argv[])
{
    Config &config = Config::getInstance();
    // 加载配置参数
    int max_retry = config.GetValue<int>("max_retries", 3);
    int retry_interval = config.GetValue<int>("retry_interval", 1000);
    // 初始化变量
    std::string host = DEFAULT_HOST;
    int port = DEFAULT_PORT;
    std::string username;
    std::string password;
    WSADATA wsaData;
    SOCKET client_socket = INVALID_SOCKET;
    struct sockaddr_in server_addr;

    // 解析命令行参数
    parse_arguments(argc, argv, host, port, username, password);
    while (username.empty() || password.empty())
    {
        std::cout << "Please input username:";
        std::cin >> username;
        std::cout << "Please input password:";
        std::cin >> password;
        std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    }
    // 初始化Winsock
    int wsaResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (wsaResult != 0)
    {
        std::cerr << "WSAStartup fail: " << wsaResult << std::endl;
        return 1;
    }

    // 创建客户端socket
    client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (client_socket == INVALID_SOCKET)
    {
        std::cerr << "build socket fail: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 设置服务器地址信息
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    // 将主机名转换为IP地址
    if (inet_pton(AF_INET, host.c_str(), &server_addr.sin_addr) <= 0)
    {
        std::cerr << "invalid server address: " << host << std::endl;
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }
    // 带重试的连接
    bool connected = false;
    for (int attempt = 0; attempt < max_retry; ++attempt)
    {
        std::cout << "connecting to " << host << ":" << port << "... (Attempt " << attempt + 1 << "/" << max_retry << ")" << std::endl;
        if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
        {
            // 如果不是最后一次尝试，则等待后重试
            if (attempt < max_retry - 1)
            {
                std::cerr << "connect fail: " << WSAGetLastError() << ". Retrying in " << retry_interval << "ms..." << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(retry_interval));
            }
            else
            {
                // 最后一次尝试失败，打印错误并退出
                std::cerr << "connect fail after " << max_retry << " attempts. Error: " << WSAGetLastError() << std::endl;
            }
        }
        else
        {
            // 连接成功
            connected = true;
            break; // 跳出循环
        }
    }

    // 如果所有重试都失败了，清理并退出程序
    if (!connected)
    {
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }
    // 首先发送检测用户名和密码
    LoginRequest login_req;
    // 使用 strncpy 确保不会溢出，并清空多余部分
    strncpy(login_req.username, username.c_str(), sizeof(login_req.username) - 1);
    login_req.username[sizeof(login_req.username) - 1] = '\0'; // 确保以null结尾
    strncpy(login_req.password, password.c_str(), sizeof(login_req.password) - 1);
    login_req.password[sizeof(login_req.password) - 1] = '\0';
    if (!send_packet(client_socket, OperationType::LOGIN_REQUEST, &login_req, sizeof(login_req)))
    {
        std::cerr << "send fail: " << WSAGetLastError() << std::endl;
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }

    LoginResponse response;
    int bytes_received = recv(client_socket, (char *)&response, sizeof(LoginResponse), 0);
    if (bytes_received <= 0)
    {
        if (bytes_received == 0)
        {
            std::cout << "server closed connection" << std::endl;
        }
        else
        {
            std::cerr << "recv fail: " << WSAGetLastError() << std::endl;
        }
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }
    if (!response.success)
    {
        std::cerr << "login fail: " << response.message << std::endl;
        close_socket(client_socket);
        WSACleanup();
        return 0;
    }

    std::cout << "success connect to MiniDB!" << std::endl;
    std::cout << "Please input SQL to server(input exit out):" << std::endl;

    std::string sql_buffer; // 用于拼接跨行SQL语句
    // 主循环:发送和接收数据
    while (true)
    {
        // 读取用户输入
        // std::cin.ignore();
        // 1. 根据缓冲区是否为空，打印不同的提示符
        if (sql_buffer.empty())
        {
            std::cout << ">> ";
        }
        else
        {
            std::cout << "-> ";
        }

        std::string line_part;
        // 2. 读取一行输入
        if (!std::getline(std::cin, line_part))
        {
            // 用户输入了 Ctrl+D (EOF)
            if (!sql_buffer.empty())
            {
                // 如果缓冲区还有未发送的内容，提醒用户
                std::cout << "\nWarning: Incomplete SQL statement in buffer. Use 'exit;' to quit." << std::endl;
            }
            else
            {
                std::cout << "\nexit..." << std::endl;
                break;
            }
            // 清空cin的错误状态，以便可以继续输入
            std::cin.clear();
            continue;
        }
        // 3. 处理行内注释
        size_t comment_pos_dash = line_part.find("--");
        if (comment_pos_dash != std::string::npos)
        {
            line_part = line_part.substr(0, comment_pos_dash);
        }
        size_t comment_pos_hash = line_part.find('#');
        if (comment_pos_hash != std::string::npos)
        {
            line_part = line_part.substr(0, comment_pos_hash);
        }

        // 4. 将处理后的行追加到缓冲区
        if (!line_part.empty())
        {
            line_part.erase(0, line_part.find_first_not_of(" \t\n\r"));
            line_part.erase(line_part.find_last_not_of(" \t\n\r") + 1);
            if (!line_part.empty())
            {
                if (!sql_buffer.empty())
                {
                    sql_buffer += " ";
                }
                sql_buffer += line_part;
            }
        }

        // 5. 循环处理缓冲区中所有以分号结束的完整语句
        size_t semi_pos;
        while ((semi_pos = sql_buffer.find(';')) != std::string::npos)
        {
            // a. 提取一条完整的 SQL 语句
            std::string single_sql = sql_buffer.substr(0, semi_pos + 1);
            sql_buffer.erase(0, semi_pos + 1);

            // b. Trim 空白字符
            single_sql.erase(0, single_sql.find_first_not_of(" \t\n\r"));
            single_sql.erase(single_sql.find_last_not_of(" \t\n\r") + 1);

            if (single_sql.empty())
            {
                continue; // 只是一个分号，忽略
            }

            // c. 检查退出命令
            if (single_sql == "exit")
            {
                std::cout << "exit..." << std::endl;
                close_socket(client_socket);
                return 0; // 正常退出
            }

            // d. 发送数据到服务器
            if (!send_packet(client_socket, OperationType::SQL_REQUEST, single_sql.c_str(), single_sql.length()))
            {
                std::cerr << "send sql request fail" << std::endl;
                goto cleanup; // 使用 goto 跳转到清理代码
            }

            // 1. 接收固定长度的消息头
            MessageHeader header;
            if (!recv_all(client_socket, (char *)&header, sizeof(MessageHeader)))
            {
                break; // 接收失败，退出循环
            }
            if (header.type != OperationType::SQL_RESPONSE)
            {
                std::cerr << "Received unSupported message type: " << static_cast<int>(header.type) << std::endl;
                break;
            }
            // 2. 将网络字节序转为主机字节序，得到消息体长度
            uint32_t body_length = ntohl(header.length);

            // 检查消息体长度是否过大，防止恶意攻击
            if (body_length > 10 * 1024 * 1024)
            { // 比如限制最大为10MB
                std::cerr << "Packet body too large: " << body_length << std::endl;
                break;
            }

            if (body_length == 0)
            {
                // 可能是一些心跳包或无内容的确认包，根据协议处理
                std::cout << "Received an empty packet." << std::endl;
                continue;
            }

            // 3. 准备缓冲区并接收完整的消息体
            std::vector<char> body_buffer(body_length);
            if (!recv_all(client_socket, body_buffer.data(), body_length))
            {
                break; // 接收失败，退出循环
            }
            try
            {
                json j = json::parse(body_buffer.data(), body_buffer.data() + body_length);
                std::cout << "received SQL response: " << j.dump(4) << std::endl;
                QueryResult result = fromJson(j);
                // Deserializer deserializer(body_buffer.data(), body_length);
                // deserializer >> result;
                if (result.status == "success")
                {
                    if (result.type == QueryType::SELECT)
                    {
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        // 打印SELECT结果（列名+行数据）
                        std::cout << "|";
                        for (auto &col : result.columns)
                            std::cout << col << "\t|";
                        std::cout << std::endl;
                        for (auto &row : result.rows)
                        {
                            std::cout << "|";
                            for (auto &val : row)
                            {
                                if (!val.has_value())
                                {
                                    std::cout << "NULL" << "\t";
                                }
                                else
                                {
                                    std::visit([](auto &&arg)
                                               { std::cout << toJson(arg); }, val.value());
                                    std::cout << "\t";
                                }
                            }
                            std::cout << std::endl;
                        }
                    }
                    else if (result.type == QueryType::SHOW_TABLES)
                    {
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        auto schemas = result.schemas;
                        for (auto &[schema_name, columns] : schemas)
                        {
                            std::cout << std::endl;
                            std::cout << schema_name << " : " << std::endl;
                            std::cout << "————————————————————————————————" << std::endl;
                            for (auto &col : columns)
                            {
                                std::cout << "" << col.name << " " << col.type << (col.type == "VARCHAR" ? "(" + std::to_string(col.length) + ")" : "") << " " << (col.nullable ? "NULL" : "NOT NULL") << " " << (col.primary ? "PRIMARY KEY" : "") << " " << (col.unique ? "UNIQUE" : "") << " " << (col.auto_increment ? "AUTO_INCREMENT" : "") << " " << (col.default_value.has_value() ? "DEFAULT " + col.default_value.value() : "") << " " << (col.comment.empty() ? "" : "COMMENT " + col.comment) << std::endl;
                            }
                            std::cout << std::endl;
                        }
                    }
                    else if (result.type == QueryType::SHOW_INDICES)
                    {
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        auto indices = result.indexes;
                        for (auto &index : indices)
                        {
                            std::cout << std::endl;
                            std::cout << index.index_name << " : " << std::endl;
                            std::cout << "————————————————————————————————" << std::endl;
                            std::cout << "columns: ";
                            for (auto &col : index.columns)
                            {
                                std::cout << col << " ";
                            }
                            std::cout << std::endl;
                            std::cout << "UNIQUE: " << index.is_unique << std::endl;
                        }
                    }
                    else
                    {
                        // 打印CREATE/INSERT结果
                        std::cout << result.message << std::endl;
                    }
                }
                else
                {
                    // 打印错误
                    std::cout << "Error: [" << result.error_type << "] " << result.message << std::endl;
                }
            }
            catch (json::parse_error &e)
            {
                std::cerr << "JSON parse error: " << e.what() << '\n'
                          << "exception id: " << e.id << '\n'
                          << "byte position of error: " << e.byte << std::endl;
            }
            catch (json::type_error &e)
            {
                std::cerr << "JSON type error: " << e.what() << std::endl;
            }
            if (sql_buffer.empty())
            {
                std::cout << ">> ";
            }
        }
    }
cleanup: // 清理标签
    // 清理资源
    closesocket(client_socket);
    WSACleanup();
    std::cout << "MiniDB exited." << std::endl;

    return 0;
}

#elif defined(__linux__)
// Linux平台的解析参数函数 (与Windows版本逻辑一致)
void parse_arguments(int argc, char *argv[], std::string &host, int &port, std::string &username, std::string &password)
{
    const struct option long_options[] = {
        {"host", required_argument, NULL, 'h'},
        {"port", required_argument, NULL, 'o'},
        {"help", no_argument, NULL, '?'},
        {"user", required_argument, NULL, 'u'},
        {"password", required_argument, NULL, 'p'},
        {NULL, 0, NULL, 0}};

    int opt;
    // 短选项字符串 "h:o:u:p:?"，冒号表示选项需要参数
    while ((opt = getopt_long(argc, argv, "h:o:u:p:?", long_options, NULL)) != -1)
    {
        switch (opt)
        {
        case 'h':
            host = optarg;
            break;
        case 'o':
            port = atoi(optarg);
            break;
        case '?':
            print_usage(argv[0]);
            exit(0);
        case 'u':
            username = optarg;
            break;
        case 'p':
            password = optarg;
            break;
        default:
            print_usage(argv[0]);
            exit(1);
        }
    }
}

int main(int argc, char *argv[])
{
    Config &config = Config::getInstance();
    // 加载配置参数
    int max_retry = config.GetValue<int>("max_retries", 3);
    int retry_interval = config.GetValue<int>("retry_interval", 1000);
    // 初始化变量
    std::string host = DEFAULT_HOST;
    int port = DEFAULT_PORT;
    std::string username;
    std::string password;
    socket_t client_socket = INVALID_SOCKET_VAL; // 使用跨平台类型
    struct sockaddr_in server_addr;

    // 解析命令行参数
    parse_arguments(argc, argv, host, port, username, password);
    while (username.empty() || password.empty())
    {
        std::cout << "Please input username:";
        std::cin >> username;
        std::cout << "Please input password:";
        std::cin >> password;
    }
    // 清理交互式输入后留下的换行符
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    // 创建客户端socket
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == INVALID_SOCKET_VAL)
    {
        perror("build socket fail"); // perror会打印更详细的错误信息
        return 1;
    }

    // 设置服务器地址信息
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    // 将主机名转换为IP地址
    if (inet_pton(AF_INET, host.c_str(), &server_addr.sin_addr) <= 0)
    {
        std::cerr << "invalid server address: " << host << std::endl;
        close_socket(client_socket);
        return 1;
    }

    // 连接到服务器，并实现重试逻辑
    bool connected = false;
    for (int attempt = 0; attempt < max_retry; ++attempt)
    {
        std::cout << "connecting to " << host << ":" << port << "... (Attempt " << attempt + 1 << "/" << max_retry << ")" << std::endl;
        if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
        {
            // 如果不是最后一次尝试，则等待后重试
            if (attempt < max_retry - 1)
            {
                perror("connect fail");
                std::cerr << "Retrying in " << retry_interval << "ms..." << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(retry_interval));
            }
            else
            {
                // 最后一次尝试失败，打印错误并退出
                perror("connect fail after all attempts");
            }
        }
        else
        {
            // 连接成功
            connected = true;
            break; // 跳出循环
        }
    }

    // 如果所有重试都失败了，清理并退出程序
    if (!connected)
    {
        close_socket(client_socket);
        return 1;
    }

    // --- 登录验证逻辑 (与Windows版本一致) ---
    LoginRequest login_req;
    strncpy(login_req.username, username.c_str(), sizeof(login_req.username) - 1);
    login_req.username[sizeof(login_req.username) - 1] = '\0';
    strncpy(login_req.password, password.c_str(), sizeof(login_req.password) - 1);
    login_req.password[sizeof(login_req.password) - 1] = '\0';

    if (!send_packet(client_socket, OperationType::LOGIN_REQUEST, &login_req, sizeof(login_req)))
    {
        std::cerr << "send login request fail" << std::endl;
        close_socket(client_socket);
        return 1;
    }

    // 在Linux上，LoginResponse也是一个固定大小的结构体，可以用recv_all来接收
    LoginResponse response;
    if (!recv_all(client_socket, (char *)&response, sizeof(LoginResponse)))
    {
        std::cerr << "receive login response fail" << std::endl;
        close_socket(client_socket);
        return 1;
    }

    if (!response.success)
    {
        std::cerr << "login fail: " << response.message << std::endl;
        close_socket(client_socket);
        return 0;
    }

    std::cout << "success connect to MiniDB!" << std::endl;
    std::cout << "Please input SQL to server(input exit out):" << std::endl;
    std::string sql_buffer; // 用于拼接跨行SQL语句
    // --- 主循环:发送和接收数据 (与Windows版本一致) ---
    while (true)
    {
        // 1. 根据缓冲区是否为空，打印不同的提示符
        if (sql_buffer.empty())
        {
            std::cout << ">> ";
        }
        else
        {
            std::cout << "-> ";
        }

        std::string line_part;
        // 2. 读取一行输入
        if (!std::getline(std::cin, line_part))
        {
            // 用户输入了 Ctrl+D (EOF)
            if (!sql_buffer.empty())
            {
                // 如果缓冲区还有未发送的内容，提醒用户
                std::cout << "\nWarning: Incomplete SQL statement in buffer. Use 'exit;' to quit." << std::endl;
            }
            else
            {
                std::cout << "\nexit..." << std::endl;
                break;
            }
            // 清空cin的错误状态，以便可以继续输入
            std::cin.clear();
            continue;
        }

        // 3. 处理行内注释
        size_t comment_pos_dash = line_part.find("--");
        if (comment_pos_dash != std::string::npos)
        {
            line_part = line_part.substr(0, comment_pos_dash);
        }
        size_t comment_pos_hash = line_part.find('#');
        if (comment_pos_hash != std::string::npos)
        {
            line_part = line_part.substr(0, comment_pos_hash);
        }

        // 4. 将处理后的行追加到缓冲区
        if (!line_part.empty())
        {
            line_part.erase(0, line_part.find_first_not_of(" \t\n\r"));
            line_part.erase(line_part.find_last_not_of(" \t\n\r") + 1);
            if (!line_part.empty())
            {
                if (!sql_buffer.empty())
                {
                    sql_buffer += " ";
                }
                sql_buffer += line_part;
            }
        }

        // 5. 循环处理缓冲区中所有以分号结束的完整语句
        size_t semi_pos;
        while ((semi_pos = sql_buffer.find(';')) != std::string::npos)
        {
            // a. 提取一条完整的 SQL 语句
            std::string single_sql = sql_buffer.substr(0, semi_pos);
            sql_buffer.erase(0, semi_pos + 1);

            // b. Trim 空白字符
            single_sql.erase(0, single_sql.find_first_not_of(" \t\n\r"));
            single_sql.erase(single_sql.find_last_not_of(" \t\n\r") + 1);

            if (single_sql.empty())
            {
                continue; // 只是一个分号，忽略
            }

            // c. 检查退出命令
            if (single_sql == "exit")
            {
                std::cout << "exit..." << std::endl;
                close_socket(client_socket);
                return 0; // 正常退出
            }

            // d. 发送数据到服务器
            if (!send_packet(client_socket, OperationType::SQL_REQUEST, single_sql.c_str(), single_sql.length()))
            {
                std::cerr << "send sql request fail" << std::endl;
                goto cleanup; // 使用 goto 跳转到清理代码
            }

            // 1. 接收固定长度的消息头
            MessageHeader header;
            if (!recv_all(client_socket, (char *)&header, sizeof(MessageHeader)))
            {
                break; // 接收失败，退出循环
            }

            if (header.type != OperationType::SQL_RESPONSE)
            {
                std::cerr << "Received unsupported message type: " << static_cast<int>(header.type) << std::endl;
                break;
            }

            // 2. 将网络字节序转为主机字节序，得到消息体长度
            uint32_t body_length = ntohl(header.length);

            if (body_length > 10 * 1024 * 1024)
            {
                std::cerr << "Packet body too large: " << body_length << std::endl;
                break;
            }
            if (body_length == 0)
            {
                std::cout << "Received an empty packet." << std::endl;
                continue;
            }

            // 3. 准备缓冲区并接收完整的消息体
            std::vector<char> body_buffer(body_length);
            if (!recv_all(client_socket, body_buffer.data(), body_length))
            {
                break; // 接收失败，退出循环
            }

            // 4. 解析和显示 (与Windows版本完全相同)
            try
            {
                json j = json::parse(body_buffer.data(), body_buffer.data() + body_length);
                std::cout << "received SQL response: " << j.dump(4) << std::endl;
                QueryResult result = fromJson(j);
                if (result.status == "success")
                {
                    if (result.type == QueryType::SELECT)
                    {
                        // ... (此处省略与Windows版本完全相同的显示代码) ...
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        for (auto &col : result.columns)
                            std::cout << col << "\t";
                        std::cout << std::endl;
                        for (auto &row : result.rows)
                        {
                            for (auto &val : row)
                            {
                                if (!val.has_value())
                                {
                                    std::cout << "NULL" << "\t";
                                }
                                else
                                {
                                    std::cout << toJson(val.value()) << "\t";
                                }
                            }
                            std::cout << std::endl;
                        }
                    }
                    else if (result.type == QueryType::SHOW_TABLES)
                    {
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        for (auto &[schema_name, columns] : result.schemas)
                        {
                            std::cout << schema_name << " : " << std::endl;
                            for (auto &col : columns)
                            {
                                std::cout << "  " << col.name << " " << col.type << (col.type == "VARCHAR" ? "(" + std::to_string(col.length) + ")" : "") << std::endl;
                            }
                        }
                    }
                    else if (result.type == QueryType::SHOW_INDICES)
                    {
                        std::cout << result.message << std::endl;
                        std::cout << "-------------------------------------------------------------------" << std::endl;
                        for (auto &index : result.indexes)
                        {
                            std::cout << index.index_name << " ON (";
                            for (size_t i = 0; i < index.columns.size(); ++i)
                            {
                                std::cout << index.columns[i] << (i == index.columns.size() - 1 ? "" : ", ");
                            }
                            std::cout << ")" << (index.is_unique ? " [UNIQUE]" : "") << std::endl;
                        }
                    }
                    else
                    {
                        std::cout << result.message << std::endl;
                    }
                }
                else
                {
                    std::cout << "Error: [" << result.error_type << "] " << result.message << std::endl;
                }
            }
            catch (json::parse_error &e)
            {
                std::cerr << "JSON parse error: " << e.what() << '\n'
                          << "exception id: " << e.id << '\n'
                          << "byte position of error: " << e.byte << std::endl;
            }
            catch (json::type_error &e)
            {
                std::cerr << "JSON type error: " << e.what() << std::endl;
            }
            // 如果执行完一条语句后缓冲区为空，就打印下一个主提示符并跳出内循环
            if (sql_buffer.empty())
            {
                std::cout << ">> ";
            }
        }
    }
cleanup:
    // 清理资源
    close_socket(client_socket);
    std::cout << "MiniDB exited." << std::endl;

    return 0;
}

#endif